#include"Common.h"
#include"BlockQueue.hpp"
#include"Task.h"

int add(int x, int y)
{
    return x + y;
}
void* produce(void* args)
{
    BlockQueue<Task>* pbq = (BlockQueue<Task>*)args;
    while(true)
    {
        int x = rand() % 10 + 1;
        int y = rand() % 10 + 1;
        Task t(x, y, add);
        pbq->push(t);
        printf("生产资源(%p)：%d + %d = ???\n", pthread_self(), x, y);
        //cout << "生产资源(" << pthread_self() << ")：" << x << "+" << y << "= ???" << endl;
    }
    return nullptr;
}
void* consume(void* args)
{
    BlockQueue<Task>* pbq = (BlockQueue<Task>*)args;
    while(true)
    {
        Task t;
        pbq->pop(&t);
        printf("消费资源(%p)：%d + %d = %d\n", pthread_self(), t.x(), t.y(), t());
        //cout << "消费资源(" << pthread_self() << ")：" << t.x() << "+" << t.y() << "=" << t() << endl;
        sleep(1);
    }
    return nullptr;
}
int main()
{
    srand((size_t)time(nullptr) ^ getpid());
    BlockQueue<Task> bq;
    pthread_t c[5];
    pthread_t p[2];

    for(int i = 0; i < 5; ++i) pthread_create(c+i, nullptr, consume, &bq);
    for(int i = 0; i < 2; ++i) pthread_create(p+i, nullptr, produce, &bq);

    for(int i = 0; i < 5; ++i) pthread_join(c[i], nullptr);
    for(int i = 0; i < 2; ++i) pthread_join(p[i], nullptr);
    return 0;
}
